package com.petter.lock.juc.semaphore;

import java.util.concurrent.Semaphore;

/**
 *
 * 实例1：
 *     public final static int SEM_SIZE = 5;
 *     public final static int THREAD_COUNT = 5;
 * t3 trying to acquire
 * t0 trying to acquire
 * t2 trying to acquire
 * t1 trying to acquire
 * t4 trying to acquire
 * t0 acquire successfully
 * t1 acquire successfully
 * t2 acquire successfully
 * t3 acquire successfully
 * t4 acquire successfully
 * t3 release successfully
 * t4 release successfully
 * t0 release successfully
 * t2 release successfully
 * t1 release successfully
 *
 * 实例2：
 *     public final static int SEM_SIZE = 5;
 *     public final static int THREAD_COUNT = 6;
 * 存在一个线程未执行完，导致程序卡主
 *
 * @author : GD
 * @date :2021/12/20 : 22:40
 */
public class Semaphore10Thread {

    public final static int SEM_SIZE = 5;
    public final static int THREAD_COUNT = 6;

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(SEM_SIZE);
        for (int i = 0; i < THREAD_COUNT; i++) {
            new MyThread2("t" + i, semaphore).start();
        }
    }
}
class MyThread2 extends Thread {
    private Semaphore semaphore;

    public MyThread2(String name, Semaphore semaphore) {
        super(name);
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " trying to acquire");
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + " acquire successfully");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + " release successfully");
        }
    }
}
